package com.atguigu.gmall.order.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.order.service.OrderService;
import com.atguigu.gmall.order.util.OrderThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * projectName: gmall
 *
 * @author: 陈鹏
 * time: 2022/10/10 20:15 星期一
 * description: 订单微服务的controller层
 */
@RestController
@RequestMapping("/api/order")
public class OrderController {

    @Resource
    private OrderService orderService;

    /**
     * 新增订单
     * @param orderInfo
     * @return
     */
    @PostMapping("/addOrder")
    public Result addOrder(@RequestBody OrderInfo orderInfo){
        orderService.addOrder(orderInfo);
        return Result.ok();
    }

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 用户取消订单
     * @param orderId
     * @return
     */
    @GetMapping(value = "/cancelOrder")
    public Result cancelOrder(Long orderId){
        //设置用户下单的计数器
        Long increment =
                redisTemplate.opsForValue().increment("User_Cancel_Order_Count_" + OrderThreadLocalUtil.get(), 1);
        if(increment > 1){
            return Result.fail();
        }
        try {
            //设置这个标识位3秒失效
            redisTemplate.expire("User_Cancel_Order_Count_" + OrderThreadLocalUtil.get(),10, TimeUnit.SECONDS);
            //取消订单
            orderService.cancelOrder(orderId);
            //返回结果
            return Result.ok();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            redisTemplate.delete("User_Cancel_Order_Count_" + OrderThreadLocalUtil.get());
        }
        return Result.fail();
    }

    /**
     * 获取支付信息
     * @param orderId
     * @param payWay
     * @return
     */
    @GetMapping(value = "/getPayInfo")
    public String getPayInfo(@RequestParam String orderId,
                             @RequestParam String payWay){
        return orderService.getPayInfo(orderId,payWay);
    };
}
